import { PureComponent } from 'react'
import { connect } from 'react-redux';
import * as action from '../../actions/user'
import { Link } from 'react-router-dom'
import Errors from '../../components/Errors'
import { store } from '../../store/index';
import {replace} from "connected-react-router"


class Login extends PureComponent {

  changeUserEmail = (ev) => {
    this.props.onEmailChange('email', ev.target.value)
  }

  changePassword = ev => {
    this.props.onPasswordChange('password', ev.target.value)
  }

  //state 是在组件里
  onSubmitForm = (email, password) => (ev) => {
    ev.preventDefault()
    //网络接口请求 ： 注册
    this.props.onSubmitUser(email, password)
  }

  render() {
    // console.log("render");
    const { email, password, errors } = this.props
    // console.log('resig password', password);
    return (
      <div className='container page'>
        <div className='row'>
          <div className='col-md-6 offset-md-3 col-xs-12'>
            <h1>登录</h1>

            {/* 调转到注册 */}
            <p className='text-xs-center'>
              <Link to='/regist'>
                没有账号，请跳转注册！
              </Link>
            </p>


            {/* 错误显示 */}
            <Errors errors={errors} />

            <form onSubmit={this.onSubmitForm(email, password)}>
              <fieldset className='form-group'>
                <input
                  className='form-control form-control-lg'
                  type="text"
                  placeholder='用户邮箱'
                  value={email}
                  onChange={this.changeUserEmail}
                />
              </fieldset>
              <fieldset className='form-group'>
                <input
                  className='form-control form-control-lg'
                  type="password"
                  placeholder='用户密码'
                  value={password}
                  onChange={this.changePassword}
                />
              </fieldset>
              <button
                className='btn btn-lg btn-primary pull-xs-right'
                type='submit'
              >
                登录
              </button>
            </form>
          </div>
        </div>
      </div>
    )
  }
  componentDidUpdate(preProps) {
    if (this.props.redirect && this.props.redirect !== preProps.redirect) {
      store.dispatch(replace(this.props.redirect))
    }
  }

  // componentWillUnmount() {
  //   this.props.onUnload()
  // }
}

//数据
const mapState = state => ({ ...state.user })

//行为
const mapDispatch = dispatch => {
  return {
    onEmailChange: (key, value) => dispatch(action.userFieldUpdate(key, value)),
    onUsernameChange: (key, value) => dispatch(action.userFieldUpdate(key, value)),
    onPasswordChange: (key, value) => dispatch(action.userFieldUpdate(key, value)),
    onSubmitUser: (email, password) => dispatch(action.loginSubmit(email, password)),
    onUnload: () => dispatch(action.unload())
  }
}


export default connect(mapState, mapDispatch)(Login)